<!DOCTYPE html><html lang="en"><head><link rel="stylesheet" href="./style.css"><title>Browser - 30 seconds of code</title><meta charset="utf-8"><meta name="description" content="Curated collection of useful Javascript snippets that you can understand in 30 seconds or less."><meta name="keywords" content="javascript, snippets, code, programming"><meta name="author" content="Angelos Chalaris (chalarangelo@gmail.com)"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#111"><meta property="og:title" content="30 seconds of code"><meta property="og:description" content="Curated collection of useful Javascript snippets that you can understand in 30 seconds or less."/><meta property="og:type" content="website"/><meta property="og:image" content="https://30secondsofcode.org/logos/logo_512.png"><link rel="icon" type="image/png" href="./logos/logo_128.png"><link rel="manifest" href="manifest.json"><script>const search = (node) => {
        if(node.value.toLowerCase().trim() === ''){
          document.querySelector('nav').querySelectorAll('li > a').forEach(x => x.style.display = ''); 
          document.querySelector('nav').querySelectorAll('h4:not(.static-link)').forEach(x => x.classList = 'collapse');
          return;
        }
        let matchingTags = [];
        Array.from(document.querySelector('nav').querySelectorAll('li')).forEach(x => {
          let data = [x.textContent.toLowerCase(), ...x.querySelector('a').getAttribute('tags').split(',')].map(v => !!(v.indexOf(node.value.toLowerCase()) + 1));
          if(data.includes(true)){
            x.style.display = '';
            matchingTags.push(x.querySelector('a').getAttribute('tags').split(',')[0]);
          }
          else x.style.display = 'none';
        });
        Array.from(document.querySelector('nav').querySelectorAll('h4:not(.static-link)')).forEach(x => {
          x.classList = matchingTags.includes(x.textContent.toLowerCase()) ? 'collapse toggled' : 'collapse';
        })
      }
      function scrollToTop(){
        const c = document.querySelector('.card-container').scrollTop;
        if (c > 0) {
          window.requestAnimationFrame(scrollToTop);
          document.querySelector('.card-container').scrollTo(0, c - c / 4);
        }
      };
      function scrollTo(element, to, id, duration) {
        if (duration <= 0) return;
        var difference = to - element.scrollTop;
        var perTick = difference / duration * 40;

        setTimeout(function() {
            element.scrollTop = element.scrollTop + perTick;
            if (element.scrollTop === to) {
              window.location.href = "#"+id;
              return;
            }
            scrollTo(element, to, id, duration - 40);
        }, 40);
      };
      function loader() {
        registerClickListener();
        if(window.innerWidth >= '768')
          document.querySelector('nav').scrollTop = Array.from(document.querySelectorAll('h4')).filter(v => v.innerHTML === 'Browser')[0].offsetTop;
        else
          document.querySelector('nav').scrollTop = Array.from(document.querySelectorAll('h4')).filter(v => v.innerHTML === 'Browser')[0].offsetTop;
      }
      function registerClickListener() {
        document.addEventListener('click', function (event) {
          if ( event.target.classList.contains('collapse') ) {
            event.target.classList = event.target.classList.contains('toggled') ? 'collapse' : 'collapse toggled';
          }
          else if (event.target.classList.contains('menu-button')) {
            document.querySelector('nav').classList = event.target.classList.contains('toggled') ? '' : 'col-nav';
            document.querySelector('[type="search"]').classList = event.target.classList.contains('toggled') ? '' : 'col-nav';
            event.target.classList = event.target.classList.contains('toggled') ? 'menu-button' : 'menu-button toggled';
          }
          else if (!document.querySelector('nav').contains(event.target) && !document.querySelector('[type="search"]').contains(event.target) && window.innerWidth < '768') {
            document.querySelector('nav').classList = '';
            document.querySelector('[type="search"]').classList = '';
            document.querySelector('.menu-button').classList = 'menu-button';
          }
          else if (event.target.classList.contains('social')){
            if (event.target.classList.contains('fb')){
              window.location = "https://www.facebook.com/30secondsofcode";
            }
            else if (event.target.classList.contains('instagram')) {
              window.location = "https://www.instagram.com/30secondsofcode";
            }
            else if (event.target.classList.contains('twitter')) {
              window.location = "https://twitter.com/30secondsofcode";
            } 
          }
          else if (event.target.classList.contains('copy-button')) {
            const text = event.target.parentElement.parentElement.querySelector(':not(pre) + pre').textContent;
            const textArea = document.createElement("textarea");
            textArea.value = text.trim();
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand("Copy");
            document.body.removeChild(textArea);
            let tst = document.createElement('div');
            tst.classList = 'toast';
            tst.innerHTML = 'Snippet copied to clipboard!';
            document.body.appendChild(tst);
            setTimeout(function() {
              tst.style.opacity = 0;
              setTimeout(function() {
                document.body.removeChild(tst);
              },300);
            },1700);
          }
        }, false);
      }</script></head><body onload="loader()" class="card-page"><a href="https://github.com/30-seconds/30-seconds-of-code" class="github-corner" aria-label="View source on Github"><svg width="56" height="56" viewBox="0 0 250 250" style="fill:#009688;color:#fff;position:fixed;top:0;border:0;right:0;z-index:1000" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><button class="menu-button"></button><header><h1 class="logo"><a href="./index"><img src="https://30secondsofcode.org/logos/logo_256.png" alt="logo"/><span id="title">&nbsp;30 seconds of code</span> <small>Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.</small></a></h1></header><div class="container card-container"><input class="search" type="search" id="searchInput" onkeyup="search(this)" placeholder="Search..." aria-label="Snippet search"><nav><h4 class="collapse">Adapter</h4><ul><li><a tags="adapter,function,intermediate" href="./adapter#ary">ary</a></li><li><a tags="adapter,function,intermediate" href="./adapter#call">call</a></li><li><a tags="adapter,function,array,intermediate" href="./adapter#collectinto">collectInto</a></li><li><a tags="adapter,function,intermediate" href="./adapter#flip">flip</a></li><li><a tags="adapter,function,intermediate" href="./adapter#over">over</a></li><li><a tags="adapter,function,intermediate" href="./adapter#overargs">overArgs</a></li><li><a tags="adapter,function,promise,intermediate" href="./adapter#pipeasyncfunctions">pipeAsyncFunctions</a></li><li><a tags="adapter,function,intermediate" href="./adapter#pipefunctions">pipeFunctions</a></li><li><a tags="adapter,function,promise,intermediate" href="./adapter#promisify">promisify</a></li><li><a tags="adapter,function,intermediate" href="./adapter#rearg">rearg</a></li><li><a tags="adapter,intermediate" href="./adapter#spreadover">spreadOver</a></li><li><a tags="adapter,function,intermediate" href="./adapter#unary">unary</a></li></ul><h4 class="collapse">Array</h4><ul><li><a tags="array,function,beginner" href="./index#all">all</a></li><li><a tags="array,function,beginner" href="./index#allequal">allEqual</a></li><li><a tags="array,function,beginner" href="./index#any">any</a></li><li><a tags="array,string,utility,intermediate" href="./index#arraytocsv">arrayToCSV</a></li><li><a tags="array,intermediate" href="./index#bifurcate">bifurcate</a></li><li><a tags="array,function,intermediate" href="./index#bifurcateby">bifurcateBy</a></li><li><a tags="array,intermediate" href="./index#chunk">chunk</a></li><li><a tags="array,beginner" href="./index#compact">compact</a></li><li><a tags="array,object,intermediate" href="./index#countby">countBy</a></li><li><a tags="array,intermediate" href="./index#countoccurrences">countOccurrences</a></li><li><a tags="array,recursion,intermediate" href="./index#deepflatten">deepFlatten</a></li><li><a tags="array,math,beginner" href="./index#difference">difference</a></li><li><a tags="array,function,intermediate" href="./index#differenceby">differenceBy</a></li><li><a tags="array,function,intermediate" href="./index#differencewith">differenceWith</a></li><li><a tags="array,beginner" href="./index#drop">drop</a></li><li><a tags="array,beginner" href="./index#dropright">dropRight</a></li><li><a tags="array,function,intermediate" href="./index#droprightwhile">dropRightWhile</a></li><li><a tags="array,function,intermediate" href="./index#dropwhile">dropWhile</a></li><li><a tags="array,beginner" href="./index#everynth">everyNth</a></li><li><a tags="array,beginner" href="./index#filternonunique">filterNonUnique</a></li><li><a tags="array,function,intermediate" href="./index#filternonuniqueby">filterNonUniqueBy</a></li><li><a tags="array,beginner" href="./index#findlast">findLast</a></li><li><a tags="array,function,intermediate" href="./index#findlastindex">findLastIndex</a></li><li><a tags="array,intermediate" href="./index#flatten">flatten</a></li><li><a tags="array,function,intermediate" href="./index#foreachright">forEachRight</a></li><li><a tags="array,object,intermediate" href="./index#groupby">groupBy</a></li><li><a tags="array,beginner" href="./index#head">head</a></li><li><a tags="array,intermediate" href="./index#indexofall">indexOfAll</a></li><li><a tags="array,beginner" href="./index#initial">initial</a></li><li><a tags="array,intermediate" href="./index#initialize2darray">initialize2DArray</a></li><li><a tags="array,math,intermediate" href="./index#initializearraywithrange">initializeArrayWithRange</a></li><li><a tags="array,math,intermediate" href="./index#initializearraywithrangeright">initializeArrayWithRangeRight</a></li><li><a tags="array,math,intermediate" href="./index#initializearraywithvalues">initializeArrayWithValues</a></li><li><a tags="array,recursion,intermediate" href="./index#initializendarray">initializeNDArray</a></li><li><a tags="array,math,intermediate" href="./index#intersection">intersection</a></li><li><a tags="array,function,intermediate" href="./index#intersectionby">intersectionBy</a></li><li><a tags="array,function,intermediate" href="./index#intersectionwith">intersectionWith</a></li><li><a tags="array,intermediate" href="./index#issorted">isSorted</a></li><li><a tags="array,intermediate" href="./index#join">join</a></li><li><a tags="array,string,object,advanced" href="./index#jsontocsv">JSONtoCSV</a></li><li><a tags="array,beginner" href="./index#last">last</a></li><li><a tags="array,string,utility,intermediate" href="./index#longestitem">longestItem</a></li><li><a tags="array,object,advanced" href="./index#mapobject">mapObject</a></li><li><a tags="array,math,beginner" href="./index#maxn">maxN</a></li><li><a tags="array,math,beginner" href="./index#minn">minN</a></li><li><a tags="array,function,beginner" href="./index#none">none</a></li><li><a tags="array,beginner" href="./index#nthelement">nthElement</a></li><li><a tags="array,beginner" href="./index#offset">offset</a></li><li><a tags="array,object,function,intermediate" href="./index#partition">partition</a></li><li><a tags="array,recursion,advanced" href="./index#permutations">permutations</a></li><li><a tags="array,intermediate" href="./index#pull">pull</a></li><li><a tags="array,advanced" href="./index#pullatindex">pullAtIndex</a></li><li><a tags="array,advanced" href="./index#pullatvalue">pullAtValue</a></li><li><a tags="array,function,advanced" href="./index#pullby">pullBy</a></li><li><a tags="array,intermediate" href="./index#reducedfilter">reducedFilter</a></li><li><a tags="array,function,intermediate" href="./index#reducesuccessive">reduceSuccessive</a></li><li><a tags="array,function,intermediate" href="./index#reducewhich">reduceWhich</a></li><li><a tags="array,beginner" href="./index#reject">reject</a></li><li><a tags="array,intermediate" href="./index#remove">remove</a></li><li><a tags="array,random,beginner" href="./index#sample">sample</a></li><li><a tags="array,random,intermediate" href="./index#samplesize">sampleSize</a></li><li><a tags="array,intermediate" href="./index#shank">shank</a></li><li><a tags="array,random,intermediate" href="./index#shuffle">shuffle</a></li><li><a tags="array,math,beginner" href="./index#similarity">similarity</a></li><li><a tags="array,math,intermediate" href="./index#sortedindex">sortedIndex</a></li><li><a tags="array,math,function,intermediate" href="./index#sortedindexby">sortedIndexBy</a></li><li><a tags="array,math,intermediate" href="./index#sortedlastindex">sortedLastIndex</a></li><li><a tags="array,math,function,intermediate" href="./index#sortedlastindexby">sortedLastIndexBy</a></li><li><a tags="array,sort,advanced,intermediate" href="./index#stablesort">stableSort</a></li><li><a tags="array,math,intermediate" href="./index#symmetricdifference">symmetricDifference</a></li><li><a tags="array,function,intermediate" href="./index#symmetricdifferenceby">symmetricDifferenceBy</a></li><li><a tags="array,function,intermediate" href="./index#symmetricdifferencewith">symmetricDifferenceWith</a></li><li><a tags="array,beginner" href="./index#tail">tail</a></li><li><a tags="array,beginner" href="./index#take">take</a></li><li><a tags="array,intermediate" href="./index#takeright">takeRight</a></li><li><a tags="array,function,intermediate" href="./index#takerightwhile">takeRightWhile</a></li><li><a tags="array,function,intermediate" href="./index#takewhile">takeWhile</a></li><li><a tags="array,intermediate" href="./index#tohash">toHash</a></li><li><a tags="array,math,beginner" href="./index#union">union</a></li><li><a tags="array,function,intermediate" href="./index#unionby">unionBy</a></li><li><a tags="array,function,intermediate" href="./index#unionwith">unionWith</a></li><li><a tags="array,beginner" href="./index#uniqueelements">uniqueElements</a></li><li><a tags="array,function,intermediate" href="./index#uniqueelementsby">uniqueElementsBy</a></li><li><a tags="array,function,intermediate" href="./index#uniqueelementsbyright">uniqueElementsByRight</a></li><li><a tags="array,math,intermediate" href="./index#uniquesymmetricdifference">uniqueSymmetricDifference</a></li><li><a tags="array,intermediate" href="./index#unzip">unzip</a></li><li><a tags="array,function,advanced" href="./index#unzipwith">unzipWith</a></li><li><a tags="array,beginner" href="./index#without">without</a></li><li><a tags="array,math,intermediate" href="./index#xprod">xProd</a></li><li><a tags="array,intermediate" href="./index#zip">zip</a></li><li><a tags="array,object,intermediate" href="./index#zipobject">zipObject</a></li><li><a tags="array,function,advanced" href="./index#zipwith">zipWith</a></li></ul><h4 class="collapse">Browser</h4><ul><li><a tags="browser,array,intermediate" href="#arraytohtmllist">arrayToHtmlList</a></li><li><a tags="browser,intermediate" href="#bottomvisible">bottomVisible</a></li><li><a tags="browser,string,advanced" href="#copytoclipboard">copyToClipboard</a></li><li><a tags="browser,advanced" href="#counter">counter</a></li><li><a tags="browser,utility,beginner" href="#createelement">createElement</a></li><li><a tags="browser,event,advanced" href="#createeventhub">createEventHub</a></li><li><a tags="browser,url,beginner" href="#currenturl">currentURL</a></li><li><a tags="browser,intermediate" href="#detectdevicetype">detectDeviceType</a></li><li><a tags="browser,intermediate" href="#elementcontains">elementContains</a></li><li><a tags="browser,advanced" href="#elementisvisibleinviewport">elementIsVisibleInViewport</a></li><li><a tags="browser,intermediate" href="#getscrollposition">getScrollPosition</a></li><li><a tags="browser,css,beginner" href="#getstyle">getStyle</a></li><li><a tags="browser,css,beginner" href="#hasclass">hasClass</a></li><li><a tags="browser,utility,advanced,promise,advanced" href="#hashbrowser">hashBrowser</a></li><li><a tags="browser,css,beginner" href="#hide">hide</a></li><li><a tags="browser,url,intermediate" href="#httpsredirect">httpsRedirect</a></li><li><a tags="browser,beginner" href="#insertafter">insertAfter</a></li><li><a tags="browser,beginner" href="#insertbefore">insertBefore</a></li><li><a tags="browser,beginner" href="#isbrowsertabfocused">isBrowserTabFocused</a></li><li><a tags="browser,array,beginner" href="#nodelisttoarray">nodeListToArray</a></li><li><a tags="browser,event,advanced" href="#observemutations">observeMutations</a></li><li><a tags="browser,event,intermediate" href="#off">off</a></li><li><a tags="browser,event,intermediate" href="#on">on</a></li><li><a tags="browser,event,advanced" href="#onuserinputchange">onUserInputChange</a></li><li><a tags="browser,utility,intermediate" href="#prefix">prefix</a></li><li><a tags="browser,utility,intermediate" href="#recordanimationframes">recordAnimationFrames</a></li><li><a tags="browser,url,beginner" href="#redirect">redirect</a></li><li><a tags="browser,function,advanced,promise,url" href="#runasync">runAsync</a></li><li><a tags="browser,intermediate" href="#scrolltotop">scrollToTop</a></li><li><a tags="browser,beginner" href="#setstyle">setStyle</a></li><li><a tags="browser,css,beginner" href="#show">show</a></li><li><a tags="browser,css,intermediate" href="#smoothscroll">smoothScroll</a></li><li><a tags="browser,beginner" href="#toggleclass">toggleClass</a></li><li><a tags="browser,event,intermediate" href="#triggerevent">triggerEvent</a></li><li><a tags="browser,utility,random,intermediate" href="#uuidgeneratorbrowser">UUIDGeneratorBrowser</a></li></ul><h4 class="collapse">Date</h4><ul><li><a tags="date,beginner" href="./date#dayofyear">dayOfYear</a></li><li><a tags="date,math,string,utility,intermediate" href="./date#formatduration">formatDuration</a></li><li><a tags="date,intermediate" href="./date#getcolontimefromdate">getColonTimeFromDate</a></li><li><a tags="date,intermediate" href="./date#getdaysdiffbetweendates">getDaysDiffBetweenDates</a></li><li><a tags="date,beginner" href="./date#getmeridiemsuffixofinteger">getMeridiemSuffixOfInteger</a></li><li><a tags="date,utility,beginner" href="./date#isafterdate">isAfterDate</a></li><li><a tags="date,utility,beginner" href="./date#isbeforedate">isBeforeDate</a></li><li><a tags="date,utility,beginner" href="./date#issamedate">isSameDate</a></li><li><a tags="date,math,beginner" href="./date#maxdate">maxDate</a></li><li><a tags="date,math,beginner" href="./date#mindate">minDate</a></li><li><a tags="date,intermediate" href="./date#tomorrow">tomorrow</a></li></ul><h4 class="collapse">Function</h4><ul><li><a tags="function,intermediate" href="./function#attempt">attempt</a></li><li><a tags="function,object,intermediate" href="./function#bind">bind</a></li><li><a tags="function,object,intermediate" href="./function#bindkey">bindKey</a></li><li><a tags="function,intermediate" href="./function#chainasync">chainAsync</a></li><li><a tags="function,intermediate" href="./function#compose">compose</a></li><li><a tags="function,intermediate" href="./function#composeright">composeRight</a></li><li><a tags="function,intermediate" href="./function#converge">converge</a></li><li><a tags="function,recursion,intermediate" href="./function#curry">curry</a></li><li><a tags="function,intermediate" href="./function#debounce">debounce</a></li><li><a tags="function,intermediate" href="./function#defer">defer</a></li><li><a tags="function,intermediate" href="./function#delay">delay</a></li><li><a tags="function,utility,beginner" href="./function#functionname">functionName</a></li><li><a tags="function,intermediate" href="./function#hz">hz</a></li><li><a tags="function,advanced" href="./function#memoize">memoize</a></li><li><a tags="function,beginner" href="./function#negate">negate</a></li><li><a tags="function,intermediate" href="./function#once">once</a></li><li><a tags="function,intermediate" href="./function#partial">partial</a></li><li><a tags="function,intermediate" href="./function#partialright">partialRight</a></li><li><a tags="function,promise,intermediate" href="./function#runpromisesinseries">runPromisesInSeries</a></li><li><a tags="function,promise,intermediate" href="./function#sleep">sleep</a></li><li><a tags="function,advanced" href="./function#throttle">throttle</a></li><li><a tags="function,intermediate" href="./function#times">times</a></li><li><a tags="function,intermediate" href="./function#uncurry">uncurry</a></li><li><a tags="function,array,intermediate" href="./function#unfold">unfold</a></li><li><a tags="function,intermediate" href="./function#when">when</a></li></ul><h4 class="collapse">Math</h4><ul><li><a tags="math,beginner" href="./math#approximatelyequal">approximatelyEqual</a></li><li><a tags="math,array,beginner" href="./math#average">average</a></li><li><a tags="math,array,function,intermediate" href="./math#averageby">averageBy</a></li><li><a tags="math,intermediate" href="./math#binomialcoefficient">binomialCoefficient</a></li><li><a tags="math,beginner" href="./math#clampnumber">clampNumber</a></li><li><a tags="math,beginner" href="./math#degreestorads">degreesToRads</a></li><li><a tags="math,array,beginner" href="./math#digitize">digitize</a></li><li><a tags="math,beginner" href="./math#distance">distance</a></li><li><a tags="math,array,advanced" href="./math#elo">elo</a></li><li><a tags="math,recursion,beginner" href="./math#factorial">factorial</a></li><li><a tags="math,array,beginner" href="./math#fibonacci">fibonacci</a></li><li><a tags="math,recursion,beginner" href="./math#gcd">gcd</a></li><li><a tags="math,intermediate" href="./math#geometricprogression">geometricProgression</a></li><li><a tags="math,beginner" href="./math#hammingdistance">hammingDistance</a></li><li><a tags="math,beginner" href="./math#inrange">inRange</a></li><li><a tags="math,beginner" href="./math#isdivisible">isDivisible</a></li><li><a tags="math,beginner" href="./math#iseven">isEven</a></li><li><a tags="math,beginner,intermediate" href="./math#isprime">isPrime</a></li><li><a tags="math,recursion,beginner" href="./math#lcm">lcm</a></li><li><a tags="math,utility,advanced" href="./math#luhncheck">luhnCheck</a></li><li><a tags="math,array,function,beginner" href="./math#maxby">maxBy</a></li><li><a tags="math,array,intermediate" href="./math#median">median</a></li><li><a tags="math,array,function,beginner" href="./math#minby">minBy</a></li><li><a tags="math,intermediate" href="./math#percentile">percentile</a></li><li><a tags="math,beginner" href="./math#powerset">powerset</a></li><li><a tags="math,array,intermediate" href="./math#primes">primes</a></li><li><a tags="math,beginner" href="./math#radstodegrees">radsToDegrees</a></li><li><a tags="math,utility,random,intermediate" href="./math#randomintarrayinrange">randomIntArrayInRange</a></li><li><a tags="math,utility,random,beginner" href="./math#randomintegerinrange">randomIntegerInRange</a></li><li><a tags="math,utility,random,beginner" href="./math#randomnumberinrange">randomNumberInRange</a></li><li><a tags="math,intermediate" href="./math#round">round</a></li><li><a tags="math,utility,intermediate" href="./math#sdbm">sdbm</a></li><li><a tags="math,array,intermediate" href="./math#standarddeviation">standardDeviation</a></li><li><a tags="math,array,beginner" href="./math#sum">sum</a></li><li><a tags="math,array,function,intermediate" href="./math#sumby">sumBy</a></li><li><a tags="math,intermediate" href="./math#sumpower">sumPower</a></li><li><a tags="math,beginner" href="./math#tosafeinteger">toSafeInteger</a></li></ul><h4 class="collapse">Node</h4><ul><li><a tags="node,string,utility,beginner" href="./node#atob">atob</a></li><li><a tags="node,string,utility,beginner" href="./node#btoa">btoa</a></li><li><a tags="node,utility,string,intermediate" href="./node#colorize">colorize</a></li><li><a tags="node,intermediate" href="./node#hasflags">hasFlags</a></li><li><a tags="node,utility,promise,intermediate" href="./node#hashnode">hashNode</a></li><li><a tags="node,type,intermediate" href="./node#isduplexstream">isDuplexStream</a></li><li><a tags="node,type,intermediate" href="./node#isreadablestream">isReadableStream</a></li><li><a tags="node,type,intermediate" href="./node#isstream">isStream</a></li><li><a tags="node,intermediate" href="./node#istravisci">isTravisCI</a></li><li><a tags="node,type,intermediate" href="./node#iswritablestream">isWritableStream</a></li><li><a tags="node,json,intermediate" href="./node#jsontofile">JSONToFile</a></li><li><a tags="node,array,string,beginner" href="./node#readfilelines">readFileLines</a></li><li><a tags="node,string,beginner" href="./node#untildify">untildify</a></li><li><a tags="node,utility,random,intermediate" href="./node#uuidgeneratornode">UUIDGeneratorNode</a></li></ul><h4 class="collapse">Object</h4><ul><li><a tags="object,function,intermediate" href="./object#bindall">bindAll</a></li><li><a tags="object,recursion,intermediate" href="./object#deepclone">deepClone</a></li><li><a tags="object,recursion,intermediate" href="./object#deepfreeze">deepFreeze</a></li><li><a tags="object,intermediate" href="./object#defaults">defaults</a></li><li><a tags="object,recursion,intermediate" href="./object#dig">dig</a></li><li><a tags="object,array,type,advanced" href="./object#equals">equals</a></li><li><a tags="object,function,intermediate" href="./object#findkey">findKey</a></li><li><a tags="object,function,intermediate" href="./object#findlastkey">findLastKey</a></li><li><a tags="object,recursion,intermediate" href="./object#flattenobject">flattenObject</a></li><li><a tags="object,intermediate" href="./object#forown">forOwn</a></li><li><a tags="object,intermediate" href="./object#forownright">forOwnRight</a></li><li><a tags="object,function,intermediate" href="./object#functions">functions</a></li><li><a tags="object,intermediate" href="./object#get">get</a></li><li><a tags="object,function,intermediate" href="./object#invertkeyvalues">invertKeyValues</a></li><li><a tags="object,intermediate" href="./object#lowercasekeys">lowercaseKeys</a></li><li><a tags="object,function,intermediate" href="./object#mapkeys">mapKeys</a></li><li><a tags="object,function,intermediate" href="./object#mapvalues">mapValues</a></li><li><a tags="object,type,intermediate" href="./object#matches">matches</a></li><li><a tags="object,type,function,intermediate" href="./object#matcheswith">matchesWith</a></li><li><a tags="object,array,intermediate" href="./object#merge">merge</a></li><li><a tags="object,intermediate" href="./object#nest">nest</a></li><li><a tags="object,array,beginner" href="./object#objectfrompairs">objectFromPairs</a></li><li><a tags="object,array,beginner" href="./object#objecttopairs">objectToPairs</a></li><li><a tags="object,array,intermediate" href="./object#omit">omit</a></li><li><a tags="object,array,function,intermediate" href="./object#omitby">omitBy</a></li><li><a tags="object,array,intermediate" href="./object#orderby">orderBy</a></li><li><a tags="object,array,intermediate" href="./object#pick">pick</a></li><li><a tags="object,array,function,intermediate" href="./object#pickby">pickBy</a></li><li><a tags="object,intermediate" href="./object#renamekeys">renameKeys</a></li><li><a tags="object,beginner" href="./object#shallowclone">shallowClone</a></li><li><a tags="object,array,string,intermediate" href="./object#size">size</a></li><li><a tags="object,array,intermediate" href="./object#transform">transform</a></li><li><a tags="object,logic,array,intermediate" href="./object#truthcheckcollection">truthCheckCollection</a></li><li><a tags="object,advanced" href="./object#unflattenobject">unflattenObject</a></li></ul><h4 class="collapse">String</h4><ul><li><a tags="string,beginner" href="./string#bytesize">byteSize</a></li><li><a tags="string,array,intermediate" href="./string#capitalize">capitalize</a></li><li><a tags="string,regexp,intermediate" href="./string#capitalizeeveryword">capitalizeEveryWord</a></li><li><a tags="string,array,utility,intermediate" href="./string#csvtoarray">CSVToArray</a></li><li><a tags="string,array,object,advanced" href="./string#csvtojson">CSVToJSON</a></li><li><a tags="string,array,intermediate" href="./string#decapitalize">decapitalize</a></li><li><a tags="string,browser,regexp,intermediate" href="./string#escapehtml">escapeHTML</a></li><li><a tags="string,regexp,intermediate" href="./string#escaperegexp">escapeRegExp</a></li><li><a tags="string,intermediate" href="./string#fromcamelcase">fromCamelCase</a></li><li><a tags="string,utility,beginner" href="./string#indentstring">indentString</a></li><li><a tags="string,utility,browser,url,intermediate" href="./string#isabsoluteurl">isAbsoluteURL</a></li><li><a tags="string,regexp,intermediate" href="./string#isanagram">isAnagram</a></li><li><a tags="string,utility,beginner" href="./string#islowercase">isLowerCase</a></li><li><a tags="string,utility,beginner" href="./string#isuppercase">isUpperCase</a></li><li><a tags="string,array,function,utility,beginner" href="./string#mapstring">mapString</a></li><li><a tags="string,utility,regexp,intermediate" href="./string#mask">mask</a></li><li><a tags="string,beginner" href="./string#pad">pad</a></li><li><a tags="string,intermediate" href="./string#palindrome">palindrome</a></li><li><a tags="string,intermediate" href="./string#pluralize">pluralize</a></li><li><a tags="string,regexp,intermediate" href="./string#removenonascii">removeNonASCII</a></li><li><a tags="string,array,beginner" href="./string#reversestring">reverseString</a></li><li><a tags="string,beginner" href="./string#sortcharactersinstring">sortCharactersInString</a></li><li><a tags="string,beginner" href="./string#splitlines">splitLines</a></li><li><a tags="string,recursion,advanced" href="./string#stringpermutations">stringPermutations</a></li><li><a tags="string,utility,regexp,beginner" href="./string#striphtmltags">stripHTMLTags</a></li><li><a tags="string,regexp,intermediate" href="./string#tocamelcase">toCamelCase</a></li><li><a tags="string,regexp,intermediate" href="./string#tokebabcase">toKebabCase</a></li><li><a tags="string,regexp,intermediate" href="./string#tosnakecase">toSnakeCase</a></li><li><a tags="string,beginner" href="./string#truncatestring">truncateString</a></li><li><a tags="string,browser,beginner" href="./string#unescapehtml">unescapeHTML</a></li><li><a tags="string,utility,regexp,advanced" href="./string#urljoin">URLJoin</a></li><li><a tags="string,regexp,intermediate" href="./string#words">words</a></li></ul><h4 class="collapse">Type</h4><ul><li><a tags="type,beginner" href="./type#gettype">getType</a></li><li><a tags="type,array,regexp,beginner" href="./type#is">is</a></li><li><a tags="type,array,intermediate" href="./type#isarraylike">isArrayLike</a></li><li><a tags="type,beginner" href="./type#isboolean">isBoolean</a></li><li><a tags="type,array,object,string,beginner" href="./type#isempty">isEmpty</a></li><li><a tags="type,function,beginner" href="./type#isfunction">isFunction</a></li><li><a tags="type,beginner" href="./type#isnil">isNil</a></li><li><a tags="type,beginner" href="./type#isnull">isNull</a></li><li><a tags="type,math,beginner" href="./type#isnumber">isNumber</a></li><li><a tags="type,object,beginner" href="./type#isobject">isObject</a></li><li><a tags="type,object,beginner" href="./type#isobjectlike">isObjectLike</a></li><li><a tags="type,object,intermediate" href="./type#isplainobject">isPlainObject</a></li><li><a tags="type,function,array,string,intermediate" href="./type#isprimitive">isPrimitive</a></li><li><a tags="type,function,promise,intermediate" href="./type#ispromiselike">isPromiseLike</a></li><li><a tags="type,string,beginner" href="./type#isstring">isString</a></li><li><a tags="type,beginner" href="./type#issymbol">isSymbol</a></li><li><a tags="type,beginner" href="./type#isundefined">isUndefined</a></li><li><a tags="type,json,intermediate" href="./type#isvalidjson">isValidJSON</a></li></ul><h4 class="collapse">Utility</h4><ul><li><a tags="utility,array,type,beginner" href="./utility#castarray">castArray</a></li><li><a tags="utility,regexp,intermediate" href="./utility#cloneregexp">cloneRegExp</a></li><li><a tags="utility,beginner" href="./utility#coalesce">coalesce</a></li><li><a tags="utility,intermediate" href="./utility#coalescefactory">coalesceFactory</a></li><li><a tags="utility,string,intermediate" href="./utility#extendhex">extendHex</a></li><li><a tags="utility,browser,string,url,intermediate" href="./utility#geturlparameters">getURLParameters</a></li><li><a tags="utility,string,math,advanced" href="./utility#hextorgb">hexToRGB</a></li><li><a tags="utility,url,browser,intermediate" href="./utility#httpget">httpGet</a></li><li><a tags="utility,url,browser,intermediate" href="./utility#httppost">httpPost</a></li><li><a tags="utility,browser,intermediate" href="./utility#isbrowser">isBrowser</a></li><li><a tags="utility,function" href="./utility#mostperformant">mostPerformant</a></li><li><a tags="utility,function,beginner" href="./utility#ntharg">nthArg</a></li><li><a tags="utility,string,intermediate" href="./utility#parsecookie">parseCookie</a></li><li><a tags="utility,string,math,advanced" href="./utility#prettybytes">prettyBytes</a></li><li><a tags="utility,random,beginner" href="./utility#randomhexcolorcode">randomHexColorCode</a></li><li><a tags="utility,intermediate" href="./utility#rgbtohex">RGBToHex</a></li><li><a tags="utility,string,intermediate" href="./utility#serializecookie">serializeCookie</a></li><li><a tags="utility,beginner" href="./utility#timetaken">timeTaken</a></li><li><a tags="utility,intermediate" href="./utility#tocurrency">toCurrency</a></li><li><a tags="utility,math,beginner" href="./utility#todecimalmark">toDecimalMark</a></li><li><a tags="utility,math,intermediate" href="./utility#toordinalsuffix">toOrdinalSuffix</a></li><li><a tags="utility,math,intermediate" href="./utility#validatenumber">validateNumber</a></li><li><a tags="utility,regexp,intermediate" href="./utility#yesno">yesNo</a></li></ul><h4 class="static-link"><a href="./archive">Archive</a></h4><h4 class="static-link"><a href="./glossary">Glossary</a></h4><h4 class="static-link"><a href="./contributing">Contributing</a></h4><h4 class="static-link"><a href="./about">About</a></h4><div><button class="social fb"></button><button class="social instagram"></button><button class="social twitter"></button></div></nav><main class="col-centered"><span id="top"><br/><br/></span><h2 class="category-name">Browser</h2><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="arraytohtmllist">arrayToHtmlList</h4><p>Converts the given array elements into <code>&lt;li&gt;</code> tags and appends them to the list of the given id.</p><p>Use <code>Array.prototype.map()</code>, <code>document.querySelector()</code>, and an anonymous inner closure to create a list of html tags.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">arrayToHtmlList</span> <span class="token operator">=</span> <span class="token punctuation">(</span>arr<span class="token punctuation">,</span> listID<span class="token punctuation">)</span> <span class="token operator">=></span>
  <span class="token punctuation">(</span>el <span class="token operator">=></span> <span class="token punctuation">(
    (</span>el <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'#'</span> <span class="token operator">+</span> listID<span class="token punctuation">)),
    (</span>el<span class="token punctuation">.</span>innerHTML <span class="token operator">+=</span> arr<span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>item <span class="token operator">=></span> <span class="token template-string"><span class="token string">`&lt;li></span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>item<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">&lt;/li>`</span></span><span class="token punctuation">).</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token string">''</span><span class="token punctuation">))
  ))();</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">arrayToHtmlList</span><span class="token punctuation">([</span><span class="token string">'item 1'</span><span class="token punctuation">,</span> <span class="token string">'item 2'</span><span class="token punctuation">],</span> <span class="token string">'myListID'</span><span class="token punctuation">);</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="bottomvisible">bottomVisible</h4><p>Returns <code>true</code> if the bottom of the page is visible, <code>false</code> otherwise.</p><p>Use <code>scrollY</code>, <code>scrollHeight</code> and <code>clientHeight</code> to determine if the bottom of the page is visible.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">bottomVisible</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span>
  document<span class="token punctuation">.</span>documentElement<span class="token punctuation">.</span>clientHeight <span class="token operator">+</span> window<span class="token punctuation">.</span>scrollY <span class="token operator">>=</span>
  <span class="token punctuation">(</span>document<span class="token punctuation">.</span>documentElement<span class="token punctuation">.</span>scrollHeight <span class="token operator">||</span> document<span class="token punctuation">.</span>documentElement<span class="token punctuation">.</span>clientHeight<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">bottomVisible</span><span class="token punctuation">();</span> <span class="token comment">// true</span>
</pre></div><div class="card code-card"><div class="corner advanced"></div><div class="section card-content"><h4 id="copytoclipboard">copyToClipboard</h4><p>⚠️ <strong>NOTICE:</strong> The same functionality can be easily implemented by using the new asynchronous Clipboard API, which is still experimental but should be used in the future instead of this snippet. Find out more about it <a href="https://github.com/w3c/clipboard-apis/blob/master/explainer.adoc#writing-to-the-clipboard">here</a>.</p><p>Copy a string to the clipboard. Only works as a result of user action (i.e. inside a <code>click</code> event listener).</p><p>Create a new <code>&lt;textarea&gt;</code> element, fill it with the supplied data and add it to the HTML document. Use <code>Selection.getRangeAt()</code>to store the selected range (if any). Use <code>document.execCommand('copy')</code> to copy to the clipboard. Remove the <code>&lt;textarea&gt;</code> element from the HTML document. Finally, use <code>Selection().addRange()</code> to recover the original selected range (if any).</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">copyToClipboard</span> <span class="token operator">=</span> str <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> el <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">createElement</span><span class="token punctuation">(</span><span class="token string">'textarea'</span><span class="token punctuation">);</span>
  el<span class="token punctuation">.</span>value <span class="token operator">=</span> str<span class="token punctuation">;</span>
  el<span class="token punctuation">.</span><span class="token function">setAttribute</span><span class="token punctuation">(</span><span class="token string">'readonly'</span><span class="token punctuation">,</span> <span class="token string">''</span><span class="token punctuation">);</span>
  el<span class="token punctuation">.</span>style<span class="token punctuation">.</span>position <span class="token operator">=</span> <span class="token string">'absolute'</span><span class="token punctuation">;</span>
  el<span class="token punctuation">.</span>style<span class="token punctuation">.</span>left <span class="token operator">=</span> <span class="token string">'-9999px'</span><span class="token punctuation">;</span>
  document<span class="token punctuation">.</span>body<span class="token punctuation">.</span><span class="token function">appendChild</span><span class="token punctuation">(</span>el<span class="token punctuation">);</span>
  <span class="token keyword">const</span> selected <span class="token operator">=</span>
    document<span class="token punctuation">.</span><span class="token function">getSelection</span><span class="token punctuation">().</span>rangeCount <span class="token operator">></span> <span class="token number">0</span> <span class="token operator">?</span> document<span class="token punctuation">.</span><span class="token function">getSelection</span><span class="token punctuation">().</span><span class="token function">getRangeAt</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">) :</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
  el<span class="token punctuation">.</span><span class="token function">select</span><span class="token punctuation">();</span>
  document<span class="token punctuation">.</span><span class="token function">execCommand</span><span class="token punctuation">(</span><span class="token string">'copy'</span><span class="token punctuation">);</span>
  document<span class="token punctuation">.</span>body<span class="token punctuation">.</span><span class="token function">removeChild</span><span class="token punctuation">(</span>el<span class="token punctuation">);</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>selected<span class="token punctuation">) {</span>
    document<span class="token punctuation">.</span><span class="token function">getSelection</span><span class="token punctuation">().</span><span class="token function">removeAllRanges</span><span class="token punctuation">();</span>
    document<span class="token punctuation">.</span><span class="token function">getSelection</span><span class="token punctuation">().</span><span class="token function">addRange</span><span class="token punctuation">(</span>selected<span class="token punctuation">);
  }
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">copyToClipboard</span><span class="token punctuation">(</span><span class="token string">'Lorem ipsum'</span><span class="token punctuation">);</span> <span class="token comment">// 'Lorem ipsum' copied to clipboard.</span>
</pre></div><div class="card code-card"><div class="corner advanced"></div><div class="section card-content"><h4 id="counter">counter</h4><p>Creates a counter with the specified range, step and duration for the specified selector.</p><p>Check if <code>step</code> has the proper sign and change it accordingly. Use <code>setInterval()</code> in combination with <code>Math.abs()</code> and <code>Math.floor()</code> to calculate the time between each new text draw. Use <code>document.querySelector().innerHTML</code> to update the value of the selected element. Omit the fourth parameter, <code>step</code>, to use a default step of <code>1</code>. Omit the fifth parameter, <code>duration</code>, to use a default duration of <code>2000</code>ms.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">counter</span> <span class="token operator">=</span> <span class="token punctuation">(</span>selector<span class="token punctuation">,</span> start<span class="token punctuation">,</span> end<span class="token punctuation">,</span> step <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">,</span> duration <span class="token operator">=</span> <span class="token number">2000</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> current <span class="token operator">=</span> start<span class="token punctuation">,</span>
    _step <span class="token operator">=</span> <span class="token punctuation">(</span>end <span class="token operator">-</span> start<span class="token punctuation">)</span> <span class="token operator">*</span> step <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token operator">? -</span>step <span class="token punctuation">:</span> step<span class="token punctuation">,</span>
    timer <span class="token operator">=</span> <span class="token function">setInterval</span><span class="token punctuation">(()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      current <span class="token operator">+=</span> _step<span class="token punctuation">;</span>
      document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span>selector<span class="token punctuation">).</span>innerHTML <span class="token operator">=</span> current<span class="token punctuation">;</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>current <span class="token operator">>=</span> end<span class="token punctuation">)</span> document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span>selector<span class="token punctuation">).</span>innerHTML <span class="token operator">=</span> end<span class="token punctuation">;</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>current <span class="token operator">>=</span> end<span class="token punctuation">)</span> <span class="token function">clearInterval</span><span class="token punctuation">(</span>timer<span class="token punctuation">);
    },</span> Math<span class="token punctuation">.</span><span class="token function">abs</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">floor</span><span class="token punctuation">(</span>duration <span class="token operator">/</span> <span class="token punctuation">(</span>end <span class="token operator">-</span> start<span class="token punctuation">))));</span>
  <span class="token keyword">return</span> timer<span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">counter</span><span class="token punctuation">(</span><span class="token string">'#my-id'</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">1000</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">2000</span><span class="token punctuation">);</span> <span class="token comment">// Creates a 2-second timer for the element with id="my-id"</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="createelement">createElement</h4><p>Creates an element from a string (without appending it to the document). If the given string contains multiple elements, only the first one will be returned.</p><p>Use <code>document.createElement()</code> to create a new element. Set its <code>innerHTML</code> to the string supplied as the argument. Use <code>ParentNode.firstElementChild</code> to return the element version of the string.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">createElement</span> <span class="token operator">=</span> str <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> el <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">createElement</span><span class="token punctuation">(</span><span class="token string">'div'</span><span class="token punctuation">);</span>
  el<span class="token punctuation">.</span>innerHTML <span class="token operator">=</span> str<span class="token punctuation">;</span>
  <span class="token keyword">return</span> el<span class="token punctuation">.</span>firstElementChild<span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> el <span class="token operator">=</span> <span class="token function">createElement</span><span class="token punctuation">(</span>
  <span class="token template-string"><span class="token string">`&lt;div class="container">
    &lt;p>Hello!&lt;/p>
  &lt;/div>`</span></span>
<span class="token punctuation">);</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>el<span class="token punctuation">.</span>className<span class="token punctuation">);</span> <span class="token comment">// 'container'</span>
</pre></div><div class="card code-card"><div class="corner advanced"></div><div class="section card-content"><h4 id="createeventhub">createEventHub</h4><p>Creates a pub/sub (<a href="https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">publish–subscribe</a>) event hub with <code>emit</code>, <code>on</code>, and <code>off</code> methods.</p><p>Use <code>Object.create(null)</code> to create an empty <code>hub</code> object that does not inherit properties from <code>Object.prototype</code>. For <code>emit</code>, resolve the array of handlers based on the <code>event</code> argument and then run each one with <code>Array.prototype.forEach()</code> by passing in the data as an argument. For <code>on</code>, create an array for the event if it does not yet exist, then use <code>Array.prototype.push()</code> to add the handler to the array. For <code>off</code>, use <code>Array.prototype.findIndex()</code> to find the index of the handler in the event array and remove it using <code>Array.prototype.splice()</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">createEventHub</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token punctuation">({</span>
  hub<span class="token punctuation">:</span> Object<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">),</span>
  <span class="token function">emit</span><span class="token punctuation">(</span>event<span class="token punctuation">,</span> data<span class="token punctuation">) {
    (</span><span class="token keyword">this</span><span class="token punctuation">.</span>hub<span class="token punctuation">[</span>event<span class="token punctuation">]</span> <span class="token operator">||</span> <span class="token punctuation">[]).</span><span class="token function">forEach</span><span class="token punctuation">(</span>handler <span class="token operator">=></span> <span class="token function">handler</span><span class="token punctuation">(</span>data<span class="token punctuation">));
  },</span>
  <span class="token function">on</span><span class="token punctuation">(</span>event<span class="token punctuation">,</span> handler<span class="token punctuation">) {</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token keyword">this</span><span class="token punctuation">.</span>hub<span class="token punctuation">[</span>event<span class="token punctuation">])</span> <span class="token keyword">this</span><span class="token punctuation">.</span>hub<span class="token punctuation">[</span>event<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">[];</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>hub<span class="token punctuation">[</span>event<span class="token punctuation">].</span><span class="token function">push</span><span class="token punctuation">(</span>handler<span class="token punctuation">);
  },</span>
  <span class="token function">off</span><span class="token punctuation">(</span>event<span class="token punctuation">,</span> handler<span class="token punctuation">) {</span>
    <span class="token keyword">const</span> i <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>hub<span class="token punctuation">[</span>event<span class="token punctuation">]</span> <span class="token operator">||</span> <span class="token punctuation">[]).</span><span class="token function">findIndex</span><span class="token punctuation">(</span>h <span class="token operator">=></span> h <span class="token operator">===</span> handler<span class="token punctuation">);</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>i <span class="token operator">> -</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token keyword">this</span><span class="token punctuation">.</span>hub<span class="token punctuation">[</span>event<span class="token punctuation">].</span><span class="token function">splice</span><span class="token punctuation">(</span>i<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">);
  }
});</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> <span class="token function-variable function">handler</span> <span class="token operator">=</span> data <span class="token operator">=></span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>data<span class="token punctuation">);</span>
<span class="token keyword">const</span> hub <span class="token operator">=</span> <span class="token function">createEventHub</span><span class="token punctuation">();</span>
<span class="token keyword">let</span> increment <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

<span class="token comment">// Subscribe: listen for different types of events</span>
hub<span class="token punctuation">.</span><span class="token function">on</span><span class="token punctuation">(</span><span class="token string">'message'</span><span class="token punctuation">,</span> handler<span class="token punctuation">);</span>
hub<span class="token punctuation">.</span><span class="token function">on</span><span class="token punctuation">(</span><span class="token string">'message'</span><span class="token punctuation">, ()</span> <span class="token operator">=></span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'Message event fired'</span><span class="token punctuation">));</span>
hub<span class="token punctuation">.</span><span class="token function">on</span><span class="token punctuation">(</span><span class="token string">'increment'</span><span class="token punctuation">, ()</span> <span class="token operator">=></span> increment<span class="token operator">++</span><span class="token punctuation">);</span>

<span class="token comment">// Publish: emit events to invoke all handlers subscribed to them, passing the data to them as an argument</span>
hub<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token string">'message'</span><span class="token punctuation">,</span> <span class="token string">'hello world'</span><span class="token punctuation">);</span> <span class="token comment">// logs 'hello world' and 'Message event fired'</span>
hub<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token string">'message'</span><span class="token punctuation">, {</span> hello<span class="token punctuation">:</span> <span class="token string">'world'</span> <span class="token punctuation">});</span> <span class="token comment">// logs the object and 'Message event fired'</span>
hub<span class="token punctuation">.</span><span class="token function">emit</span><span class="token punctuation">(</span><span class="token string">'increment'</span><span class="token punctuation">);</span> <span class="token comment">// `increment` variable is now 1</span>

<span class="token comment">// Unsubscribe: stop a specific handler from listening to the 'message' event</span>
hub<span class="token punctuation">.</span><span class="token function">off</span><span class="token punctuation">(</span><span class="token string">'message'</span><span class="token punctuation">,</span> handler<span class="token punctuation">);</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="currenturl">currentURL</h4><p>Returns the current URL.</p><p>Use <code>window.location.href</code> to get current URL.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">currentURL</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> window<span class="token punctuation">.</span>location<span class="token punctuation">.</span>href<span class="token punctuation">;</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">currentURL</span><span class="token punctuation">();</span> <span class="token comment">// 'https://google.com'</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="detectdevicetype">detectDeviceType</h4><p>Detects wether the website is being opened in a mobile device or a desktop/laptop.</p><p>Use a regular expression to test the <code>navigator.userAgent</code> property to figure out if the device is a mobile device or a desktop/laptop.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">detectDeviceType</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span>
  <span class="token regex">/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i</span><span class="token punctuation">.</span><span class="token function">test</span><span class="token punctuation">(</span>navigator<span class="token punctuation">.</span>userAgent<span class="token punctuation">)</span>
    <span class="token operator">?</span> <span class="token string">'Mobile'</span>
    <span class="token punctuation">:</span> <span class="token string">'Desktop'</span><span class="token punctuation">;</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">detectDeviceType</span><span class="token punctuation">();</span> <span class="token comment">// "Mobile" or "Desktop"</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="elementcontains">elementContains</h4><p>Returns <code>true</code> if the <code>parent</code> element contains the <code>child</code> element, <code>false</code> otherwise.</p><p>Check that <code>parent</code> is not the same element as <code>child</code>, use <code>parent.contains(child)</code> to check if the <code>parent</code> element contains the <code>child</code> element.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">elementContains</span> <span class="token operator">=</span> <span class="token punctuation">(</span>parent<span class="token punctuation">,</span> child<span class="token punctuation">)</span> <span class="token operator">=></span> parent <span class="token operator">!==</span> child <span class="token operator">&amp;&amp;</span> parent<span class="token punctuation">.</span><span class="token function">contains</span><span class="token punctuation">(</span>child<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">elementContains</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'head'</span><span class="token punctuation">),</span> document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'title'</span><span class="token punctuation">));</span> <span class="token comment">// true</span>
<span class="token function">elementContains</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'body'</span><span class="token punctuation">),</span> document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'body'</span><span class="token punctuation">));</span> <span class="token comment">// false</span>
</pre></div><div class="card code-card"><div class="corner advanced"></div><div class="section card-content"><h4 id="elementisvisibleinviewport">elementIsVisibleInViewport</h4><p>Returns <code>true</code> if the element specified is visible in the viewport, <code>false</code> otherwise.</p><p>Use <code>Element.getBoundingClientRect()</code> and the <code>window.inner(Width|Height)</code> values to determine if a given element is visible in the viewport. Omit the second argument to determine if the element is entirely visible, or specify <code>true</code> to determine if it is partially visible.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">elementIsVisibleInViewport</span> <span class="token operator">=</span> <span class="token punctuation">(</span>el<span class="token punctuation">,</span> partiallyVisible <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> <span class="token punctuation">{</span> top<span class="token punctuation">,</span> left<span class="token punctuation">,</span> bottom<span class="token punctuation">,</span> right <span class="token punctuation">}</span> <span class="token operator">=</span> el<span class="token punctuation">.</span><span class="token function">getBoundingClientRect</span><span class="token punctuation">();</span>
  <span class="token keyword">const</span> <span class="token punctuation">{</span> innerHeight<span class="token punctuation">,</span> innerWidth <span class="token punctuation">}</span> <span class="token operator">=</span> window<span class="token punctuation">;</span>
  <span class="token keyword">return</span> partiallyVisible
    <span class="token operator">?</span> <span class="token punctuation">((</span>top <span class="token operator">></span> <span class="token number">0</span> <span class="token operator">&amp;&amp;</span> top <span class="token operator">&lt;</span> innerHeight<span class="token punctuation">)</span> <span class="token operator">||</span> <span class="token punctuation">(</span>bottom <span class="token operator">></span> <span class="token number">0</span> <span class="token operator">&amp;&amp;</span> bottom <span class="token operator">&lt;</span> innerHeight<span class="token punctuation">))</span> <span class="token operator">&amp;&amp;</span>
        <span class="token punctuation">((</span>left <span class="token operator">></span> <span class="token number">0</span> <span class="token operator">&amp;&amp;</span> left <span class="token operator">&lt;</span> innerWidth<span class="token punctuation">)</span> <span class="token operator">||</span> <span class="token punctuation">(</span>right <span class="token operator">></span> <span class="token number">0</span> <span class="token operator">&amp;&amp;</span> right <span class="token operator">&lt;</span> innerWidth<span class="token punctuation">))
    :</span> top <span class="token operator">>=</span> <span class="token number">0</span> <span class="token operator">&amp;&amp;</span> left <span class="token operator">>=</span> <span class="token number">0</span> <span class="token operator">&amp;&amp;</span> bottom <span class="token operator">&lt;=</span> innerHeight <span class="token operator">&amp;&amp;</span> right <span class="token operator">&lt;=</span> innerWidth<span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token comment">// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}</span>
<span class="token function">elementIsVisibleInViewport</span><span class="token punctuation">(</span>el<span class="token punctuation">);</span> <span class="token comment">// false - (not fully visible)</span>
<span class="token function">elementIsVisibleInViewport</span><span class="token punctuation">(</span>el<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">);</span> <span class="token comment">// true - (partially visible)</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="getscrollposition">getScrollPosition</h4><p>Returns the scroll position of the current page.</p><p>Use <code>pageXOffset</code> and <code>pageYOffset</code> if they are defined, otherwise <code>scrollLeft</code> and <code>scrollTop</code>. You can omit <code>el</code> to use a default value of <code>window</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">getScrollPosition</span> <span class="token operator">=</span> <span class="token punctuation">(</span>el <span class="token operator">=</span> window<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">({</span>
  x<span class="token punctuation">:</span> el<span class="token punctuation">.</span>pageXOffset <span class="token operator">!==</span> undefined <span class="token operator">?</span> el<span class="token punctuation">.</span>pageXOffset <span class="token punctuation">:</span> el<span class="token punctuation">.</span>scrollLeft<span class="token punctuation">,</span>
  y<span class="token punctuation">:</span> el<span class="token punctuation">.</span>pageYOffset <span class="token operator">!==</span> undefined <span class="token operator">?</span> el<span class="token punctuation">.</span>pageYOffset <span class="token punctuation">:</span> el<span class="token punctuation">.</span>scrollTop
<span class="token punctuation">});</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">getScrollPosition</span><span class="token punctuation">();</span> <span class="token comment">// {x: 0, y: 200}</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="getstyle">getStyle</h4><p>Returns the value of a CSS rule for the specified element.</p><p>Use <code>Window.getComputedStyle()</code> to get the value of the CSS rule for the specified element.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">getStyle</span> <span class="token operator">=</span> <span class="token punctuation">(</span>el<span class="token punctuation">,</span> ruleName<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token function">getComputedStyle</span><span class="token punctuation">(</span>el<span class="token punctuation">)[</span>ruleName<span class="token punctuation">];</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">getStyle</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'p'</span><span class="token punctuation">),</span> <span class="token string">'font-size'</span><span class="token punctuation">);</span> <span class="token comment">// '16px'</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="hasclass">hasClass</h4><p>Returns <code>true</code> if the element has the specified class, <code>false</code> otherwise.</p><p>Use <code>element.classList.contains()</code> to check if the element has the specified class.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">hasClass</span> <span class="token operator">=</span> <span class="token punctuation">(</span>el<span class="token punctuation">,</span> className<span class="token punctuation">)</span> <span class="token operator">=></span> el<span class="token punctuation">.</span>classList<span class="token punctuation">.</span><span class="token function">contains</span><span class="token punctuation">(</span>className<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">hasClass</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'p.special'</span><span class="token punctuation">),</span> <span class="token string">'special'</span><span class="token punctuation">);</span> <span class="token comment">// true</span>
</pre></div><div class="card code-card"><div class="corner advanced"></div><div class="section card-content"><h4 id="hashbrowser">hashBrowser</h4><p>Creates a hash for a value using the <a href="https://en.wikipedia.org/wiki/SHA-2">SHA-256</a> algorithm. Returns a promise.</p><p>Use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto">SubtleCrypto</a> API to create a hash for the given value.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">hashBrowser</span> <span class="token operator">=</span> val <span class="token operator">=></span>
  crypto<span class="token punctuation">.</span>subtle<span class="token punctuation">.</span><span class="token function">digest</span><span class="token punctuation">(</span><span class="token string">'SHA-256'</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">TextEncoder</span><span class="token punctuation">(</span><span class="token string">'utf-8'</span><span class="token punctuation">).</span><span class="token function">encode</span><span class="token punctuation">(</span>val<span class="token punctuation">)).</span><span class="token function">then</span><span class="token punctuation">(</span>h <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">let</span> hexes <span class="token operator">=</span> <span class="token punctuation">[],</span>
      view <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DataView</span><span class="token punctuation">(</span>h<span class="token punctuation">);</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> view<span class="token punctuation">.</span>byteLength<span class="token punctuation">;</span> i <span class="token operator">+=</span> <span class="token number">4</span><span class="token punctuation">)</span>
      hexes<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">((</span><span class="token string">'00000000'</span> <span class="token operator">+</span> view<span class="token punctuation">.</span><span class="token function">getUint32</span><span class="token punctuation">(</span>i<span class="token punctuation">).</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token number">16</span><span class="token punctuation">)).</span><span class="token function">slice</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">8</span><span class="token punctuation">));</span>
    <span class="token keyword">return</span> hexes<span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token string">''</span><span class="token punctuation">);
  });</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">hashBrowser</span><span class="token punctuation">(</span><span class="token constant">JSON</span><span class="token punctuation">.</span><span class="token function">stringify</span><span class="token punctuation">({</span> a<span class="token punctuation">:</span> <span class="token string">'a'</span><span class="token punctuation">,</span> b<span class="token punctuation">: [</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">],</span> foo<span class="token punctuation">: {</span> c<span class="token punctuation">:</span> <span class="token string">'bar'</span> <span class="token punctuation">} })).</span><span class="token function">then</span><span class="token punctuation">(</span>console<span class="token punctuation">.</span>log<span class="token punctuation">);</span> <span class="token comment">// '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="hide">hide</h4><p>Hides all the elements specified.</p><p>Use <code>NodeList.prototype.forEach()</code> to apply <code>display: none</code> to each element specified.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">hide</span> <span class="token operator">=</span> els <span class="token operator">=></span> els<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span>e <span class="token operator">=></span> <span class="token punctuation">(</span>e<span class="token punctuation">.</span>style<span class="token punctuation">.</span>display <span class="token operator">=</span> <span class="token string">'none'</span><span class="token punctuation">));</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">hide</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span><span class="token function">querySelectorAll</span><span class="token punctuation">(</span><span class="token string">'img'</span><span class="token punctuation">));</span> <span class="token comment">// Hides all &lt;img> elements on the page</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="httpsredirect">httpsRedirect</h4><p>Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.</p><p>Use <code>location.protocol</code> to get the protocol currently being used. If it's not HTTPS, use <code>location.replace()</code> to replace the existing page with the HTTPS version of the page. Use <code>location.href</code> to get the full address, split it with <code>String.prototype.split()</code> and remove the protocol part of the URL.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">httpsRedirect</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>location<span class="token punctuation">.</span>protocol <span class="token operator">!==</span> <span class="token string">'https:'</span><span class="token punctuation">)</span> location<span class="token punctuation">.</span><span class="token function">replace</span><span class="token punctuation">(</span><span class="token string">'https://'</span> <span class="token operator">+</span> location<span class="token punctuation">.</span>href<span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">'//'</span><span class="token punctuation">)[</span><span class="token number">1</span><span class="token punctuation">]);
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">httpsRedirect</span><span class="token punctuation">();</span> <span class="token comment">// If you are on http://mydomain.com, you are redirected to https://mydomain.com</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="insertafter">insertAfter</h4><p>Inserts an HTML string after the end of the specified element.</p><p>Use <code>el.insertAdjacentHTML()</code> with a position of <code>'afterend'</code> to parse <code>htmlString</code> and insert it after the end of <code>el</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">insertAfter</span> <span class="token operator">=</span> <span class="token punctuation">(</span>el<span class="token punctuation">,</span> htmlString<span class="token punctuation">)</span> <span class="token operator">=></span> el<span class="token punctuation">.</span><span class="token function">insertAdjacentHTML</span><span class="token punctuation">(</span><span class="token string">'afterend'</span><span class="token punctuation">,</span> htmlString<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">insertAfter</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">'myId'</span><span class="token punctuation">),</span> <span class="token string">'&lt;p>after&lt;/p>'</span><span class="token punctuation">);</span> <span class="token comment">// &lt;div id="myId">...&lt;/div> &lt;p>after&lt;/p></span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="insertbefore">insertBefore</h4><p>Inserts an HTML string before the start of the specified element.</p><p>Use <code>el.insertAdjacentHTML()</code> with a position of <code>'beforebegin'</code> to parse <code>htmlString</code> and insert it before the start of <code>el</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">insertBefore</span> <span class="token operator">=</span> <span class="token punctuation">(</span>el<span class="token punctuation">,</span> htmlString<span class="token punctuation">)</span> <span class="token operator">=></span> el<span class="token punctuation">.</span><span class="token function">insertAdjacentHTML</span><span class="token punctuation">(</span><span class="token string">'beforebegin'</span><span class="token punctuation">,</span> htmlString<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">insertBefore</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">'myId'</span><span class="token punctuation">),</span> <span class="token string">'&lt;p>before&lt;/p>'</span><span class="token punctuation">);</span> <span class="token comment">// &lt;p>before&lt;/p> &lt;div id="myId">...&lt;/div></span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="isbrowsertabfocused">isBrowserTabFocused</h4><p>Returns <code>true</code> if the browser tab of the page is focused, <code>false</code> otherwise.</p><p>Use the <code>Document.hidden</code> property, introduced by the Page Visibility API to check if the browser tab of the page is visible or hidden.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">isBrowserTabFocused</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=> !</span>document<span class="token punctuation">.</span>hidden<span class="token punctuation">;</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">isBrowserTabFocused</span><span class="token punctuation">();</span> <span class="token comment">// true</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="nodelisttoarray">nodeListToArray</h4><p>Converts a <code>NodeList</code> to an array.</p><p>Use spread operator inside new array to convert a <code>NodeList</code> to an array.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">nodeListToArray</span> <span class="token operator">=</span> nodeList <span class="token operator">=></span> <span class="token punctuation">[</span><span class="token operator">...</span>nodeList<span class="token punctuation">];</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">nodeListToArray</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span>childNodes<span class="token punctuation">);</span> <span class="token comment">// [ &lt;!DOCTYPE html>, html ]</span>
</pre></div><div class="card code-card"><div class="corner advanced"></div><div class="section card-content"><h4 id="observemutations">observeMutations</h4><p>Returns a new MutationObserver and runs the provided callback for each mutation on the specified element.</p><p>Use a <a href="https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver"><code>MutationObserver</code></a> to observe mutations on the given element. Use <code>Array.prototype.forEach()</code> to run the callback for each mutation that is observed. Omit the third argument, <code>options</code>, to use the default <a href="https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#MutationObserverInit">options</a> (all <code>true</code>).</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">observeMutations</span> <span class="token operator">=</span> <span class="token punctuation">(</span>element<span class="token punctuation">,</span> callback<span class="token punctuation">,</span> options<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> observer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MutationObserver</span><span class="token punctuation">(</span>mutations <span class="token operator">=></span> mutations<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span>m <span class="token operator">=></span> <span class="token function">callback</span><span class="token punctuation">(</span>m<span class="token punctuation">)));</span>
  observer<span class="token punctuation">.</span><span class="token function">observe</span><span class="token punctuation">(</span>
    element<span class="token punctuation">,</span>
    Object<span class="token punctuation">.</span><span class="token function">assign</span><span class="token punctuation">(
      {</span>
        childList<span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
        attributes<span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
        attributeOldValue<span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
        characterData<span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
        characterDataOldValue<span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
        subtree<span class="token punctuation">:</span> <span class="token boolean">true</span>
      <span class="token punctuation">},</span>
      options
    <span class="token punctuation">)
  );</span>
  <span class="token keyword">return</span> observer<span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> obs <span class="token operator">=</span> <span class="token function">observeMutations</span><span class="token punctuation">(</span>document<span class="token punctuation">,</span> console<span class="token punctuation">.</span>log<span class="token punctuation">);</span> <span class="token comment">// Logs all mutations that happen on the page</span>
obs<span class="token punctuation">.</span><span class="token function">disconnect</span><span class="token punctuation">();</span> <span class="token comment">// Disconnects the observer and stops logging mutations on the page</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="off">off</h4><p>Removes an event listener from an element.</p><p>Use <code>EventTarget.removeEventListener()</code> to remove an event listener from an element. Omit the fourth argument <code>opts</code> to use <code>false</code> or specify it based on the options used when the event listener was added.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">off</span> <span class="token operator">=</span> <span class="token punctuation">(</span>el<span class="token punctuation">,</span> evt<span class="token punctuation">,</span> fn<span class="token punctuation">,</span> opts <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">)</span> <span class="token operator">=></span> el<span class="token punctuation">.</span><span class="token function">removeEventListener</span><span class="token punctuation">(</span>evt<span class="token punctuation">,</span> fn<span class="token punctuation">,</span> opts<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> <span class="token function-variable function">fn</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'!'</span><span class="token punctuation">);</span>
document<span class="token punctuation">.</span>body<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">'click'</span><span class="token punctuation">,</span> fn<span class="token punctuation">);</span>
<span class="token function">off</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span>body<span class="token punctuation">,</span> <span class="token string">'click'</span><span class="token punctuation">,</span> fn<span class="token punctuation">);</span> <span class="token comment">// no longer logs '!' upon clicking on the page</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="on">on</h4><p>Adds an event listener to an element with the ability to use event delegation.</p><p>Use <code>EventTarget.addEventListener()</code> to add an event listener to an element. If there is a <code>target</code> property supplied to the options object, ensure the event target matches the target specified and then invoke the callback by supplying the correct <code>this</code> context. Returns a reference to the custom delegator function, in order to be possible to use with <a href="#off"><code>off</code></a>. Omit <code>opts</code> to default to non-delegation behavior and event bubbling.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">on</span> <span class="token operator">=</span> <span class="token punctuation">(</span>el<span class="token punctuation">,</span> evt<span class="token punctuation">,</span> fn<span class="token punctuation">,</span> opts <span class="token operator">=</span> <span class="token punctuation">{})</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> <span class="token function-variable function">delegatorFn</span> <span class="token operator">=</span> e <span class="token operator">=></span> e<span class="token punctuation">.</span>target<span class="token punctuation">.</span><span class="token function">matches</span><span class="token punctuation">(</span>opts<span class="token punctuation">.</span>target<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> fn<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>e<span class="token punctuation">.</span>target<span class="token punctuation">,</span> e<span class="token punctuation">);</span>
  el<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span>evt<span class="token punctuation">,</span> opts<span class="token punctuation">.</span>target <span class="token operator">?</span> delegatorFn <span class="token punctuation">:</span> fn<span class="token punctuation">,</span> opts<span class="token punctuation">.</span>options <span class="token operator">||</span> <span class="token boolean">false</span><span class="token punctuation">);</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>opts<span class="token punctuation">.</span>target<span class="token punctuation">)</span> <span class="token keyword">return</span> delegatorFn<span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> <span class="token function-variable function">fn</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'!'</span><span class="token punctuation">);</span>
<span class="token function">on</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span>body<span class="token punctuation">,</span> <span class="token string">'click'</span><span class="token punctuation">,</span> fn<span class="token punctuation">);</span> <span class="token comment">// logs '!' upon clicking the body</span>
<span class="token function">on</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span>body<span class="token punctuation">,</span> <span class="token string">'click'</span><span class="token punctuation">,</span> fn<span class="token punctuation">, {</span> target<span class="token punctuation">:</span> <span class="token string">'p'</span> <span class="token punctuation">});</span> <span class="token comment">// logs '!' upon clicking a `p` element child of the body</span>
<span class="token function">on</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span>body<span class="token punctuation">,</span> <span class="token string">'click'</span><span class="token punctuation">,</span> fn<span class="token punctuation">, {</span> options<span class="token punctuation">:</span> <span class="token boolean">true</span> <span class="token punctuation">});</span> <span class="token comment">// use capturing instead of bubbling</span>
</pre></div><div class="card code-card"><div class="corner advanced"></div><div class="section card-content"><h4 id="onuserinputchange">onUserInputChange</h4><p>Run the callback whenever the user input type changes (<code>mouse</code> or <code>touch</code>). Useful for enabling/disabling code depending on the input device. This process is dynamic and works with hybrid devices (e.g. touchscreen laptops).</p><p>Use two event listeners. Assume <code>mouse</code> input initially and bind a <code>touchstart</code> event listener to the document. On <code>touchstart</code>, add a <code>mousemove</code> event listener to listen for two consecutive <code>mousemove</code> events firing within 20ms, using <code>performance.now()</code>. Run the callback with the input type as an argument in either of these situations.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">onUserInputChange</span> <span class="token operator">=</span> callback <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> type <span class="token operator">=</span> <span class="token string">'mouse'</span><span class="token punctuation">,</span>
    lastTime <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
  <span class="token keyword">const</span> <span class="token function-variable function">mousemoveHandler</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> now <span class="token operator">=</span> performance<span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">();</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>now <span class="token operator">-</span> lastTime <span class="token operator">&lt;</span> <span class="token number">20</span><span class="token punctuation">)
      (</span>type <span class="token operator">=</span> <span class="token string">'mouse'</span><span class="token punctuation">),</span> <span class="token function">callback</span><span class="token punctuation">(</span>type<span class="token punctuation">),</span> document<span class="token punctuation">.</span><span class="token function">removeEventListener</span><span class="token punctuation">(</span><span class="token string">'mousemove'</span><span class="token punctuation">,</span> mousemoveHandler<span class="token punctuation">);</span>
    lastTime <span class="token operator">=</span> now<span class="token punctuation">;
  };</span>
  document<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">'touchstart'</span><span class="token punctuation">, ()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>type <span class="token operator">===</span> <span class="token string">'touch'</span><span class="token punctuation">)</span> <span class="token keyword">return</span><span class="token punctuation">;
    (</span>type <span class="token operator">=</span> <span class="token string">'touch'</span><span class="token punctuation">),</span> <span class="token function">callback</span><span class="token punctuation">(</span>type<span class="token punctuation">),</span> document<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">'mousemove'</span><span class="token punctuation">,</span> mousemoveHandler<span class="token punctuation">);
  });
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">onUserInputChange</span><span class="token punctuation">(</span>type <span class="token operator">=></span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'The user is now using'</span><span class="token punctuation">,</span> type<span class="token punctuation">,</span> <span class="token string">'as an input method.'</span><span class="token punctuation">);
});</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="prefix">prefix</h4><p>Returns the prefixed version (if necessary) of a CSS property that the browser supports.</p><p>Use <code>Array.prototype.findIndex()</code> on an array of vendor prefix strings to test if <code>document.body</code> has one of them defined in its <code>CSSStyleDeclaration</code> object, otherwise return <code>null</code>. Use <code>String.prototype.charAt()</code> and <code>String.prototype.toUpperCase()</code> to capitalize the property, which will be appended to the vendor prefix string.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">prefix</span> <span class="token operator">=</span> prop <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> capitalizedProp <span class="token operator">=</span> prop<span class="token punctuation">.</span><span class="token function">charAt</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">).</span><span class="token function">toUpperCase</span><span class="token punctuation">()</span> <span class="token operator">+</span> prop<span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">);</span>
  <span class="token keyword">const</span> prefixes <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">''</span><span class="token punctuation">,</span> <span class="token string">'webkit'</span><span class="token punctuation">,</span> <span class="token string">'moz'</span><span class="token punctuation">,</span> <span class="token string">'ms'</span><span class="token punctuation">,</span> <span class="token string">'o'</span><span class="token punctuation">];</span>
  <span class="token keyword">const</span> i <span class="token operator">=</span> prefixes<span class="token punctuation">.</span><span class="token function">findIndex</span><span class="token punctuation">(</span>
    prefix <span class="token operator">=></span> <span class="token keyword">typeof</span> document<span class="token punctuation">.</span>body<span class="token punctuation">.</span>style<span class="token punctuation">[</span>prefix <span class="token operator">?</span> prefix <span class="token operator">+</span> capitalizedProp <span class="token punctuation">:</span> prop<span class="token punctuation">]</span> <span class="token operator">!==</span> <span class="token string">'undefined'</span>
  <span class="token punctuation">);</span>
  <span class="token keyword">return</span> i <span class="token operator">!== -</span><span class="token number">1</span> <span class="token operator">?</span> <span class="token punctuation">(</span>i <span class="token operator">===</span> <span class="token number">0</span> <span class="token operator">?</span> prop <span class="token punctuation">:</span> prefixes<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">+</span> capitalizedProp<span class="token punctuation">) :</span> <span class="token keyword">null</span><span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">prefix</span><span class="token punctuation">(</span><span class="token string">'appearance'</span><span class="token punctuation">);</span> <span class="token comment">// 'appearance' on a supported browser, otherwise 'webkitAppearance', 'mozAppearance', 'msAppearance' or 'oAppearance'</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="recordanimationframes">recordAnimationFrames</h4><p>Invokes the provided callback on each animation frame.</p><p>Use recursion. Provided that <code>running</code> is <code>true</code>, continue invoking <code>window.requestAnimationFrame()</code> which invokes the provided callback. Return an object with two methods <code>start</code> and <code>stop</code> to allow manual control of the recording. Omit the second argument, <code>autoStart</code>, to implicitly call <code>start</code> when the function is invoked.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">recordAnimationFrames</span> <span class="token operator">=</span> <span class="token punctuation">(</span>callback<span class="token punctuation">,</span> autoStart <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> running <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
    raf<span class="token punctuation">;</span>
  <span class="token keyword">const</span> <span class="token function-variable function">stop</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    running <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token function">cancelAnimationFrame</span><span class="token punctuation">(</span>raf<span class="token punctuation">);
  };</span>
  <span class="token keyword">const</span> <span class="token function-variable function">start</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    running <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token function">run</span><span class="token punctuation">();
  };</span>
  <span class="token keyword">const</span> <span class="token function-variable function">run</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    raf <span class="token operator">=</span> <span class="token function">requestAnimationFrame</span><span class="token punctuation">(()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token function">callback</span><span class="token punctuation">();</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>running<span class="token punctuation">)</span> <span class="token function">run</span><span class="token punctuation">();
    });
  };</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>autoStart<span class="token punctuation">)</span> <span class="token function">start</span><span class="token punctuation">();</span>
  <span class="token keyword">return</span> <span class="token punctuation">{</span> start<span class="token punctuation">,</span> stop <span class="token punctuation">};
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> <span class="token function-variable function">cb</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'Animation frame fired'</span><span class="token punctuation">);</span>
<span class="token keyword">const</span> recorder <span class="token operator">=</span> <span class="token function">recordAnimationFrames</span><span class="token punctuation">(</span>cb<span class="token punctuation">);</span> <span class="token comment">// logs 'Animation frame fired' on each animation frame</span>
recorder<span class="token punctuation">.</span><span class="token function">stop</span><span class="token punctuation">();</span> <span class="token comment">// stops logging</span>
recorder<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">();</span> <span class="token comment">// starts again</span>
<span class="token keyword">const</span> recorder2 <span class="token operator">=</span> <span class="token function">recordAnimationFrames</span><span class="token punctuation">(</span>cb<span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">);</span> <span class="token comment">// `start` needs to be explicitly called to begin recording frames</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="redirect">redirect</h4><p>Redirects to a specified URL.</p><p>Use <code>window.location.href</code> or <code>window.location.replace()</code> to redirect to <code>url</code>. Pass a second argument to simulate a link click (<code>true</code> - default) or an HTTP redirect (<code>false</code>).</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">redirect</span> <span class="token operator">=</span> <span class="token punctuation">(</span>url<span class="token punctuation">,</span> asLink <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token operator">=></span>
  asLink <span class="token operator">?</span> <span class="token punctuation">(</span>window<span class="token punctuation">.</span>location<span class="token punctuation">.</span>href <span class="token operator">=</span> url<span class="token punctuation">) :</span> window<span class="token punctuation">.</span>location<span class="token punctuation">.</span><span class="token function">replace</span><span class="token punctuation">(</span>url<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">redirect</span><span class="token punctuation">(</span><span class="token string">'https://google.com'</span><span class="token punctuation">);</span>
</pre></div><div class="card code-card"><div class="corner advanced"></div><div class="section card-content"><h4 id="runasync">runAsync</h4><p>Runs a function in a separate thread by using a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Web Worker</a>, allowing long running functions to not block the UI.</p><p>Create a new <code>Worker</code> using a <code>Blob</code> object URL, the contents of which should be the stringified version of the supplied function. Immediately post the return value of calling the function back. Return a promise, listening for <code>onmessage</code> and <code>onerror</code> events and resolving the data posted back from the worker, or throwing an error.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">runAsync</span> <span class="token operator">=</span> fn <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> worker <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Worker</span><span class="token punctuation">(</span>
    <span class="token constant">URL</span><span class="token punctuation">.</span><span class="token function">createObjectURL</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Blob</span><span class="token punctuation">([</span><span class="token template-string"><span class="token string">`postMessage((</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>fn<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">)());`</span></span><span class="token punctuation">]), {</span>
      type<span class="token punctuation">:</span> <span class="token string">'application/javascript; charset=utf-8'</span>
    <span class="token punctuation">})
  );</span>
  <span class="token keyword">return new</span> <span class="token class-name">Promise</span><span class="token punctuation">((</span>res<span class="token punctuation">,</span> rej<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    worker<span class="token punctuation">.</span><span class="token function-variable function">onmessage</span> <span class="token operator">=</span> <span class="token punctuation">({</span> data <span class="token punctuation">})</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token function">res</span><span class="token punctuation">(</span>data<span class="token punctuation">),</span> worker<span class="token punctuation">.</span><span class="token function">terminate</span><span class="token punctuation">();
    };</span>
    worker<span class="token punctuation">.</span><span class="token function-variable function">onerror</span> <span class="token operator">=</span> err <span class="token operator">=></span> <span class="token punctuation">{</span>
      <span class="token function">rej</span><span class="token punctuation">(</span>err<span class="token punctuation">),</span> worker<span class="token punctuation">.</span><span class="token function">terminate</span><span class="token punctuation">();
    };
  });
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> <span class="token function-variable function">longRunningFunction</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> result <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
  <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">1000</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">) {</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> j <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> j <span class="token operator">&lt;</span> <span class="token number">700</span><span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">) {</span>
      <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> k <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> k <span class="token operator">&lt;</span> <span class="token number">300</span><span class="token punctuation">;</span> k<span class="token operator">++</span><span class="token punctuation">) {</span>
        result <span class="token operator">=</span> result <span class="token operator">+</span> i <span class="token operator">+</span> j <span class="token operator">+</span> k<span class="token punctuation">;
      }
    }
  }</span>
  <span class="token keyword">return</span> result<span class="token punctuation">;
};</span>
<span class="token comment">/*
  NOTE: Since the function is running in a different context, closures are not supported.
  The function supplied to `runAsync` gets stringified, so everything becomes literal.
  All variables and functions must be defined inside.
*/</span>
<span class="token function">runAsync</span><span class="token punctuation">(</span>longRunningFunction<span class="token punctuation">).</span><span class="token function">then</span><span class="token punctuation">(</span>console<span class="token punctuation">.</span>log<span class="token punctuation">);</span> <span class="token comment">// 209685000000</span>
<span class="token function">runAsync</span><span class="token punctuation">(()</span> <span class="token operator">=></span> <span class="token number">10</span> <span class="token operator">**</span> <span class="token number">3</span><span class="token punctuation">).</span><span class="token function">then</span><span class="token punctuation">(</span>console<span class="token punctuation">.</span>log<span class="token punctuation">);</span> <span class="token comment">// 1000</span>
<span class="token keyword">let</span> outsideVariable <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">;</span>
<span class="token function">runAsync</span><span class="token punctuation">(()</span> <span class="token operator">=></span> <span class="token keyword">typeof</span> outsideVariable<span class="token punctuation">).</span><span class="token function">then</span><span class="token punctuation">(</span>console<span class="token punctuation">.</span>log<span class="token punctuation">);</span> <span class="token comment">// 'undefined'</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="scrolltotop">scrollToTop</h4><p>Smooth-scrolls to the top of the page.</p><p>Get distance from top using <code>document.documentElement.scrollTop</code> or <code>document.body.scrollTop</code>. Scroll by a fraction of the distance from the top. Use <code>window.requestAnimationFrame()</code> to animate the scrolling.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">scrollToTop</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> c <span class="token operator">=</span> document<span class="token punctuation">.</span>documentElement<span class="token punctuation">.</span>scrollTop <span class="token operator">||</span> document<span class="token punctuation">.</span>body<span class="token punctuation">.</span>scrollTop<span class="token punctuation">;</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>c <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">) {</span>
    window<span class="token punctuation">.</span><span class="token function">requestAnimationFrame</span><span class="token punctuation">(</span>scrollToTop<span class="token punctuation">);</span>
    window<span class="token punctuation">.</span><span class="token function">scrollTo</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> c <span class="token operator">-</span> c <span class="token operator">/</span> <span class="token number">8</span><span class="token punctuation">);
  }
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">scrollToTop</span><span class="token punctuation">();</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="setstyle">setStyle</h4><p>Sets the value of a CSS rule for the specified element.</p><p>Use <code>element.style</code> to set the value of the CSS rule for the specified element to <code>val</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">setStyle</span> <span class="token operator">=</span> <span class="token punctuation">(</span>el<span class="token punctuation">,</span> ruleName<span class="token punctuation">,</span> val<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">(</span>el<span class="token punctuation">.</span>style<span class="token punctuation">[</span>ruleName<span class="token punctuation">]</span> <span class="token operator">=</span> val<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">setStyle</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'p'</span><span class="token punctuation">),</span> <span class="token string">'font-size'</span><span class="token punctuation">,</span> <span class="token string">'20px'</span><span class="token punctuation">);</span> <span class="token comment">// The first &lt;p> element on the page will have a font-size of 20px</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="show">show</h4><p>Shows all the elements specified.</p><p>Use the spread operator (<code>...</code>) and <code>Array.prototype.forEach()</code> to clear the <code>display</code> property for each element specified.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">show</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token operator">...</span>el<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">[</span><span class="token operator">...</span>el<span class="token punctuation">].</span><span class="token function">forEach</span><span class="token punctuation">(</span>e <span class="token operator">=></span> <span class="token punctuation">(</span>e<span class="token punctuation">.</span>style<span class="token punctuation">.</span>display <span class="token operator">=</span> <span class="token string">''</span><span class="token punctuation">));</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">show</span><span class="token punctuation">(</span><span class="token operator">...</span>document<span class="token punctuation">.</span><span class="token function">querySelectorAll</span><span class="token punctuation">(</span><span class="token string">'img'</span><span class="token punctuation">));</span> <span class="token comment">// Shows all &lt;img> elements on the page</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="smoothscroll">smoothScroll</h4><p>Smoothly scrolls the element on which it's called into the visible area of the browser window.</p><p>Use <code>.scrollIntoView</code> method to scroll the element. Pass <code>{ behavior: 'smooth' }</code> to <code>.scrollIntoView</code> so it scrolls smoothly.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">smoothScroll</span> <span class="token operator">=</span> element <span class="token operator">=></span>
  document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span>element<span class="token punctuation">).</span><span class="token function">scrollIntoView</span><span class="token punctuation">({</span>
    behavior<span class="token punctuation">:</span> <span class="token string">'smooth'</span>
  <span class="token punctuation">});</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">smoothScroll</span><span class="token punctuation">(</span><span class="token string">'#fooBar'</span><span class="token punctuation">);</span> <span class="token comment">// scrolls smoothly to the element with the id fooBar</span>
<span class="token function">smoothScroll</span><span class="token punctuation">(</span><span class="token string">'.fooBar'</span><span class="token punctuation">);</span> <span class="token comment">// scrolls smoothly to the first element with a class of fooBar</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="toggleclass">toggleClass</h4><p>Toggle a class for an element.</p><p>Use <code>element.classList.toggle()</code> to toggle the specified class for the element.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">toggleClass</span> <span class="token operator">=</span> <span class="token punctuation">(</span>el<span class="token punctuation">,</span> className<span class="token punctuation">)</span> <span class="token operator">=></span> el<span class="token punctuation">.</span>classList<span class="token punctuation">.</span><span class="token function">toggle</span><span class="token punctuation">(</span>className<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">toggleClass</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'p.special'</span><span class="token punctuation">),</span> <span class="token string">'special'</span><span class="token punctuation">);</span> <span class="token comment">// The paragraph will not have the 'special' class anymore</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="triggerevent">triggerEvent</h4><p>Triggers a specific event on a given element, optionally passing custom data.</p><p>Use <code>new CustomEvent()</code> to create an event from the specified <code>eventType</code> and details. Use <code>el.dispatchEvent()</code> to trigger the newly created event on the given element. Omit the third argument, <code>detail</code>, if you do not want to pass custom data to the triggered event.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">triggerEvent</span> <span class="token operator">=</span> <span class="token punctuation">(</span>el<span class="token punctuation">,</span> eventType<span class="token punctuation">,</span> detail<span class="token punctuation">)</span> <span class="token operator">=></span>
  el<span class="token punctuation">.</span><span class="token function">dispatchEvent</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">CustomEvent</span><span class="token punctuation">(</span>eventType<span class="token punctuation">, {</span> detail <span class="token punctuation">}));</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">triggerEvent</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">'myId'</span><span class="token punctuation">),</span> <span class="token string">'click'</span><span class="token punctuation">);</span>
<span class="token function">triggerEvent</span><span class="token punctuation">(</span>document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">'myId'</span><span class="token punctuation">),</span> <span class="token string">'click'</span><span class="token punctuation">, {</span> username<span class="token punctuation">:</span> <span class="token string">'bob'</span> <span class="token punctuation">});</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="uuidgeneratorbrowser">UUIDGeneratorBrowser</h4><p>Generates a UUID in a browser.</p><p>Use <code>crypto</code> API to generate a UUID, compliant with <a href="https://www.ietf.org/rfc/rfc4122.txt">RFC4122</a> version 4.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">UUIDGeneratorBrowser</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span>
  <span class="token punctuation">([</span><span class="token number">1e7</span><span class="token punctuation">]</span> <span class="token operator">+ -</span><span class="token number">1e3</span> <span class="token operator">+ -</span><span class="token number">4e3</span> <span class="token operator">+ -</span><span class="token number">8e3</span> <span class="token operator">+ -</span><span class="token number">1e11</span><span class="token punctuation">).</span><span class="token function">replace</span><span class="token punctuation">(</span><span class="token regex">/[018]/g</span><span class="token punctuation">,</span> c <span class="token operator">=></span>
    <span class="token punctuation">(</span>c <span class="token operator">^</span> <span class="token punctuation">(</span>crypto<span class="token punctuation">.</span><span class="token function">getRandomValues</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Uint8Array</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">))[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">&amp;</span> <span class="token punctuation">(</span><span class="token number">15</span> <span class="token operator">>></span> <span class="token punctuation">(</span>c <span class="token operator">/</span> <span class="token number">4</span><span class="token punctuation">)))).</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token number">16</span><span class="token punctuation">)
  );</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">UUIDGeneratorBrowser</span><span class="token punctuation">();</span> <span class="token comment">// '7982fcfe-5721-4632-bede-6000885be57d'</span>
</pre></div></main><footer class="col-full-width container"><div class="col-centered"><p style="display:inline-block"><strong>30 seconds of code</strong> is licensed under the <a href="https://github.com/30-seconds/30-seconds-of-code/blob/master/LICENSE">CC0-1.0</a> license.<br>Logos made by <a href="https://github.com/Chalarangelo">Angelos Chalaris</a> and ribbon made by <a href="https://github.com/tholman/github-corners">Tim Holman</a> are licensed under the <a href="https://opensource.org/licenses/MIT">MIT</a> license.<br>Sponsored by <img src="https://30secondsofcode.org/sponsors/DO_Logo_icon_blue.svg" style="vertical-align:sub;padding-right:2px;padding-left:2px" width="20px" height="20px"><a href="https://www.digitalocean.com" alt="DigitalOcean"><span style="color:#0080ff">DigitalOcean</span></a>.</p><br/><p style="display:inline-block"><a href="./about">About</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="./contributing">Contributing</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="./archive">Archive</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="./glossary">Glossary</a></p></div></footer><a class="scroll-to-top" href="#top"></a></div></body></html>